from Data import search_file
import win32com.client
import os


def gener(options=None):
    if options is None:
        options = {
            'close_revision': False,
            'accept_revision': False,
            'delete_annotations': False,
            'update_content': False,
            'delete_revision_table': False,
            'is_folder': True
        }

    # 根据选择方式调用不同的文件选择函数
    if options.get('is_folder'):
        filepaths = search_file.select_folder()
    else:
        filepaths = search_file.select_file()

    if filepaths == "-1":
        return "-1"
    if filepaths:
        word = win32com.client.Dispatch("Word.Application")
        word.Visible = True
        try:
            for file in filepaths:
                if "~" in file:
                    continue
                else:
                    # 统一使用 os.path 处理文件名
                    filename = os.path.basename(file)
                    doc = word.Documents.Open(file)
                    if options.get('close_revision'):
                        close_revision(doc, filename)
                    if options.get('accept_revision'):
                        accept_revision(doc, filename)
                    if options.get('delete_annotations'):
                        delete_annotations(doc, filename)
                    if options.get('update_content'):
                        update_content(doc, filename)
                    if options.get('delete_revision_table'):
                        delete_revision_table(doc, filename)
                    doc.Save()
                    doc.Close()
                    print("---------------------------------------------------------------------")
            print("程序执行完成！！！")
        except Exception as e:
            print(e)
        finally:
            # print()
            word.Quit()


# 关闭修订
def close_revision(doc, filename):
    doc.TrackRevisions = False
    print(f"{filename}：已关闭修订")


# 接受所有修订
def accept_revision(doc, filename):
    doc.Revisions.AcceptAll()
    print(f"{filename}：已接受修订")


# 删除所有批注
def delete_annotations(doc, filename):
    try:
        word_version = float(doc.Application.Version)

        if word_version < 16.0:  # Word 2013
            # 获取批注数量
            comment_count = 0
            for i in range(doc.Comments.Count):
                comment_count += 1
            if comment_count > 0:
                doc.DeleteAllComments()
        else:  # Word 2016及以上
            if doc.Comments.count > 0:
                doc.DeleteAllComments()
        print(f"{filename}：已删除批注")
    except Exception as e:
        print(f"{filename}：删除批注时出错: {str(e)}")


def delete_revision_table(doc, filename):
    try:
        word_version = float(doc.Application.Version)
        # 切换到打印视图
        doc.ActiveWindow.View.Type = 3  # wdPrintView
        flag = False

        if word_version < 16.0:  # Word 2013
            # 遍历段落查找修订记录
            for j in range(1, 101):
                if "修订记录" in doc.Paragraphs(j).Range.Text:
                    try:
                        # 获取修订记录段落后的第一个表格
                        current_range = doc.Paragraphs(j).Range
                        next_range = doc.Range(current_range.End, doc.Content.End)

                        # 修改：使用 Item 方法检查是否存在表格
                        try:
                            table = next_range.Tables.Item(1)
                            # 如果能获取到表格，说明存在表格
                            next_para = table.Range.Paragraphs.Last.Next()
                            table.Delete()
                            if next_para:
                                next_para.Range.Delete()
                        except:
                            # 如果获取表格失败，说明没有表格
                            pass

                        # 删除包含修订记录的段落
                        doc.Paragraphs(j).Style = "Text-1级"
                        doc.Paragraphs(j).Range.Delete()
                        flag = True
                        break
                    except Exception as e:
                        print(f"删除过程出错: {str(e)}")
                        continue
        else:  # Word 2016及以上
            # 遍历段落查找修订记录
            for j in range(1, 101):
                if "修订记录" in doc.Paragraphs(j).Range.Text:
                    try:
                        current_range = doc.Paragraphs(j).Range
                        next_range = doc.Range(current_range.End, doc.Content.End)
                        if next_range.Tables.Count > 0:
                            table = next_range.Tables(1)
                            next_para = table.Range.Paragraphs.Last.Next()
                            table.Delete()
                            if next_para:
                                next_para.Range.Delete()
                        doc.Paragraphs(j).Style = "Text-1级"
                        doc.Paragraphs(j).Range.Delete()
                        flag = True
                        break
                    except Exception as e:
                        print(f"删除过程出错: {str(e)}")
                        continue

        if flag:
            print(f"{filename}：已删除修订记录表")
        else:
            print(f"{filename}：未找到修订记录表")
    except Exception as e:
        print(f"{filename}：删除修订记录表时出错: {str(e)}")


def update_content(doc, filename):
    try:
        word_version = float(doc.Application.Version)

        # 更新所有域
        doc.Fields.Update()

        # 根据Word版本分别处理目录更新
        if word_version < 16.0:  # Word 2013
            # 检查目录数量
            toc_count = 0
            for i in range(doc.TablesOfContents.Count):
                toc_count += 1
            if toc_count > 0:
                doc.TablesOfContents(1).Update()
        else:  # Word 2016及以上
            if doc.TablesOfContents.count > 0:
                doc.TablesOfContents(1).Update()

        print(f"{filename}：已更新全文域")
    except Exception as e:
        print(f"{filename}：更新全文域时出错: {str(e)}")


if __name__ == '__main__':
    gener()
